
#define GL_GLEXT_PROTOTYPES

#include "openglframe.h"
#include "skelanim/skeletonLoader.h"
#include "skelanim/motionLoader.h"
#include <algorithm>

OpenGLFrame::OpenGLFrame (QWidget* parent, const QGLWidget* shareWidget, Qt::WFlags f)
   : QGLWidget (parent, shareWidget, f), 
     arcball(1,1) {
   
   // for keyboard use 
   setFocusPolicy(Qt::StrongFocus);
   
   cursor3D = Point3(0,0,0);
   interactionMode = VIEW_MODE;
   
   animator = 0;
   motion = 0;
   skeleton = 0;
   texFloor = 0;
   
   fovy = 40.0;
   zoomFactor = 1.0;
   meshrendermode_mask = 0x20;
   
   isProjOrtho = true; // orthographic projection
   is_lightingOn = true;
   
   viewitems_mask = 0x0; 
   viewitems_mask = viewitems_mask | MODELDEF;
   viewitems_mask = viewitems_mask | SKELETONDEF;
   viewitems_mask = viewitems_mask | KEYPOINTS;
   viewitems_mask = viewitems_mask | CONSTRAINTS;
   viewitems_mask = viewitems_mask | FLOOR;
   viewitems_mask = viewitems_mask | INFO;
   
   // Floor and shadow specificacion
   floor[0] = Point3(-4.5,-1.0, 4.5);
   floor[1] = Point3( 4.5,-1.0, 4.5);
   floor[2] = Point3( 4.5,-1.0,-4.5);
   floor[3] = Point3(-4.5,-1.0,-4.5);
   pfloor = Plane3(floor[0], floor[2], floor[1]);
   
   float l[] = {3.0, 5.0, 5.0}; // Coordinates of the light source
   float e[] = {0.0, -0.99, 0.0};  // Point of the floor plane
   float n[] = {0.0, -1.0, 0.0}; // Normal vector for the plane
   createShadowProjectionMatrix(l,e,n);
   
   currentFrame = 0;
}

OpenGLFrame::~OpenGLFrame() {
   
   if (skeleton!=0)        delete skeleton;
}

/// Sets the interaction mode
void OpenGLFrame::setInteractionMode (InteractionMode m) {
   
   interactionMode = m;
}

bool OpenGLFrame::loadSkeleton(const QString& filename) {
   
   QFileInfo fi(filename);
   QString extension = fi.suffix();
   
   GSkeleton *newskeleton = 0;
   if (extension == "asf") {
      SkeletonLoader sl;
      Skeleton *s = sl.load(filename.toStdString());
      newskeleton = new GSkeleton(*s);
      delete s;
   }
   else
      return false;
   
   if (newskeleton) {
      if (skeleton != 0) delete skeleton;
      skeleton = newskeleton;
      
      makeCurrent();
      cout<<"skeleton->nBones():::: "<<skeleton->nBones()<<endl;
      cout<<"skeleton->center(): "<<skeleton->center()<<endl;
      cout<<"skeleton->radius(): "<<skeleton->radius()<<endl;
      genWorldLimits(skeleton->center(), skeleton->radius());
      setGLview();
      
      cout<<":::::::::::::::::::::: "<<endl;
      
      sceneT.identity();
      return true;
   }
   return false;
}

bool OpenGLFrame::loadMotion(const QString& filename) {
   
   QFileInfo fi(filename);
   QString extension = fi.suffix();
   
   Motion *newmotion = 0;
   if (extension == "amc") {
      MotionLoader ml;
      newmotion = ml.load(filename.toStdString());
   }
   else
      return false;
   
   if (newmotion) {
      if (motion != 0) delete motion;
      motion = newmotion;
      cout<<"motion->getMotionSize(): "<<motion->getMotionSize()<<endl;
      
      if (animator != 0) delete animator;
      animator = new Animator(skeleton, motion);
      return true;
   }
   return false;
}

/// OpenGL initialization.
void OpenGLFrame::initializeGL() {
   
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHT1);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_NORMALIZE);
   
   // lighting setup
   GLfloat left_light_position[] =  {0.0f, 2.0f, 2.0f, 0.0f};
   GLfloat right_light_position[] = {0.0f, -2.0f, 2.0f, 0.0f};
   GLfloat left_diffuse_light[] =  {1.0f, 1.0f, 1.0f, 1.0f};
   GLfloat right_diffuse_light[] = {1.0f, 1.0f, 1.0f, 1.0f};
   GLfloat color_front[] = {0.0f, 0.5f, 1.0f, 1.0f};
   GLfloat colr_back[] = {1.0f, 0.0f, 0.0f, 1.0f};
   
   glLightfv(GL_LIGHT0, GL_POSITION, left_light_position);
   glLightfv(GL_LIGHT1, GL_POSITION, right_light_position);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, left_diffuse_light);
   glLightfv(GL_LIGHT1, GL_DIFFUSE, right_diffuse_light);
   glMaterialfv(GL_FRONT, GL_DIFFUSE, color_front);
   glMaterialfv(GL_BACK, GL_DIFFUSE, colr_back);
   
   glClearColor(1,1,1,1);
   glColor4f(1,1,0,1);
   meshrendermode_mask = SMOOTH;
   sceneT.identity();
   
   std::time(&start);
   frame = 0;
   
   genWorldLimits();
   
   texFloor = new Texture("icons/floor4.png", GL_TEXTURE_2D);
   //~ setGLview();
}

/// A simple opengl drawing callback
void OpenGLFrame::paintGL() {
   
   //~ setGLview();
   
   //~ glClearStencil(0x1);
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   gluLookAt(cameye[0],cameye[1],cameye[2],camcenter[0],camcenter[1],camcenter[2],0,1,0);
   
   if (skeleton == 0) return;
   
   // Draw the 3D cursor
   const Number &scalefactor = (maxcoo[0]-mincoo[0])*(1.5/100);
   drawCursor3D(cursor3D, scalefactor);
   
   glMultMatrixf(&sceneT);
   
   // Draw the floor
   //~ if ((viewitems_mask & FLOOR) == FLOOR)
      //~ drawFloor();
   
   // Draw the skeleton
   if ((viewitems_mask & MODELDEF) == MODELDEF)
      glDrawSkeletonBones(skeleton);
   
   // FPS info
   if ((viewitems_mask & INFO) == INFO)
      renderInfo();
}

void OpenGLFrame::renderInfo() {
   
   // Render info
   if ((viewitems_mask & INFO) == INFO and skeleton != 0) {
      glDisable(GL_LIGHTING);
      glDisable(GL_DEPTH_TEST);
      
      frame++;
      std::time(&end);
      double ddifftime = std::difftime(end, start);
      if (ddifftime > 1) {
         cfps = frame/ddifftime;
         start = end;
         frame = 0;
      }
      
      QString strInfoFrames=QString("Frames: %1").arg(motion->getMotionSize());
      QString strInfoCurrentFrame=QString("CurrentFrame: %1").arg(currentFrame);
      QString strInfoFPS=QString("FPS: %1").arg(cfps,7,'f',1);
      
      glColor4f(0.0, 0.0, 0.0, 1.0);
      renderText(30,15, strInfoFrames);
      renderText(30,30, strInfoCurrentFrame);
      renderText(30,75, strInfoFPS);
      
      glEnable(GL_LIGHTING);
      glEnable(GL_DEPTH_TEST);
   }
}

void OpenGLFrame::drawFloor() {
   
   glEnable(GL_TEXTURE_2D);
   texFloor->bind();
   
   glDisable(GL_LIGHTING);
   glPolygonMode(GL_FRONT, GL_FILL);
   glPolygonMode(GL_BACK, GL_LINE);
   glColor3f(1.0,1.0,1.0);
   glBegin(GL_QUADS);
   glNormal3f(0.0,1.0,0.0);
   glTexCoord2d(0.0,0.0); glVertex3f(floor[0][0],floor[0][1], floor[0][2]);
   glTexCoord2d(1.0,0.0); glVertex3f(floor[1][0],floor[1][1], floor[1][2]);
   glTexCoord2d(1.0,1.0); glVertex3f(floor[2][0],floor[2][1], floor[2][2]);
   glTexCoord2d(0.0,1.0); glVertex3f(floor[3][0],floor[3][1], floor[3][2]);
   glEnd();
   glEnable(GL_LIGHTING);
   glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
   
   glDisable(GL_TEXTURE_2D);
}

void OpenGLFrame::createShadowProjectionMatrix(float *l, float *e, float *n) {
   
   // These are c and d (corresponding to the tutorial)
   float d = n[0]*l[0] + n[1]*l[1] + n[2]*l[2];
   float c = e[0]*n[0] + e[1]*n[1] + e[2]*n[2] - d;
   
   // Create the matrix. OpenGL uses column by column ordering
   shadowMatrix[0]  = l[0]*n[0]+c;
   shadowMatrix[4]  = n[1]*l[0];
   shadowMatrix[8]  = n[2]*l[0];
   shadowMatrix[12] = -l[0]*c-l[0]*d;
  
   shadowMatrix[1]  = n[0]*l[1];
   shadowMatrix[5]  = l[1]*n[1]+c;
   shadowMatrix[9]  = n[2]*l[1];
   shadowMatrix[13] = -l[1]*c-l[1]*d;
  
   shadowMatrix[2]  = n[0]*l[2];
   shadowMatrix[6]  = n[1]*l[2];
   shadowMatrix[10] = l[2]*n[2]+c;
   shadowMatrix[14] = -l[2]*c-l[2]*d;
  
   shadowMatrix[3]  = n[0];
   shadowMatrix[7]  = n[1];
   shadowMatrix[11] = n[2];
   shadowMatrix[15] = -d;
}

void OpenGLFrame::genWorldLimits(Point3 center, Number radius) {
   
   /*
   if (skeleton != 0) {
      //~ mincoo[0] = skeleton->minPoint[0]; mincoo[1] = skeleton->minPoint[1]; mincoo[2] = skeleton->minPoint[2];
      //~ maxcoo[0] = skeleton->maxPoint[0]; maxcoo[1] = skeleton->maxPoint[1]; maxcoo[2] = skeleton->maxPoint[2];
   }
   else {
      mincoo[0] = -1; mincoo[1] = -1; mincoo[2] = -1;
      maxcoo[0] =  1; maxcoo[1] =  1; maxcoo[2] =  1;
   }
   */
   
   
   mincoo[0] = -1; mincoo[1] = -1; mincoo[2] = -1;
   maxcoo[0] =  1; maxcoo[1] =  1; maxcoo[2] =  1;
   
   float xc = mincoo[0] + 0.5*(maxcoo[0]-mincoo[0]);
   float yc = mincoo[1] + 0.5*(maxcoo[1]-mincoo[1]);
   
   float WorldWidth  = abs(maxcoo[0]-mincoo[0]);
   float WorldHeight = abs(maxcoo[1]-mincoo[1]);
   
   if ((WorldHeight/WorldWidth) > ((float)height()/(float)width())) {
      WorldWidth = WorldHeight / ((float)height()/(float)width());
   }
   else if ((WorldHeight/WorldWidth) < ((float)height()/(float)width())) {
      WorldHeight = WorldWidth * ((float)height()/(float)width());
   }
   
   // world limits
   mincoo[0] = xc - 0.5*WorldWidth;
   mincoo[1] = yc - 0.5*WorldHeight;
   
   maxcoo[0] = xc + 0.5*WorldWidth;
   maxcoo[1] = yc + 0.5*WorldHeight;
   
   // center camera
   camcenter[0] = xc;
   camcenter[1] = yc;
   camcenter[2] = mincoo[2] + 0.5*(maxcoo[2]-mincoo[2]);
   
   
   /// //////////
   
   //~ // the camera points to
   //~ camcenter[0] = center.x();
   //~ camcenter[1] = center.y();
   //~ camcenter[2] = center.z();
   
   //~ // the camera position
   //~ cameye[0] = camcenter[0];
   //~ cameye[1] = camcenter[1];
   //~ cameye[2] = 2.0*radius;
   
   //~ nearplane = radius;
   //~ farplane = nearplane + 2.0*radius;
   //~ leftplane = -radius;
   //~ rightplane = radius;
   //~ bottomplane = -radius;
   //~ topplane = radius;
   
   //~ GLdouble aspect = (GLdouble)width()/(GLdouble)height();
   //~ if (aspect < 1.0) { // window taller than wide
      //~ bottomplane /= aspect;
      //~ topplane /= aspect;
   //~ }
   //~ else {
      //~ leftplane *= aspect;
      //~ rightplane *= aspect;
   //~ }
}

/// It sets the projection/modelview matrices
void OpenGLFrame::setGLview() {
   
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   
   WorldWidth  = abs(maxcoo[0]-mincoo[0])*0.5;
   WorldHeight = abs(maxcoo[1]-mincoo[1])*0.5;
   
   objDistance = 0.8660*(maxcoo[1]-mincoo[1]); /// sqrt(3)/2 = 0.8660
   //~ objDistance = WorldHeight;
   nearplane = objDistance - objDistance*0.5;
   farplane  = nearplane + 20.0;
   
   cameye[0] = camcenter[0];
   cameye[1] = camcenter[1];
   cameye[2] = maxcoo[2] + objDistance;
   
   if (isProjOrtho) 
      glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
              -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
               nearplane, farplane);
   else 
      gluPerspective(fovy*zoomFactor, (GLfloat)width()/(GLfloat)height(), nearplane, farplane);
   
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glViewport(0, 0, width(), height());
}
   
/// A simple resize callback.
/// @param width the width of the new window.
/// @param height the height of the new window.
void OpenGLFrame::resizeGL(int width, int height) {
   
   setGLview();
   arcball.setBounds(width, height);  //Update mouse bounds for the arcball
}

/// Callback for handling mouse button press.
/// @param event encapsulates the event's info.
void OpenGLFrame::mousePressEvent(QMouseEvent *event) {
   
   xini=event->x(); yini=height()-event->y();
   if (event->button() == Qt::MidButton) {
      arcball.click(xini,yini);
   }
   else if (event->button() == Qt::RightButton) {
      grabLast = grabStart = screenToWorld(xini, yini);
   }
   sceneIniT = sceneT;
   glDraw();
}

/// Callback for handling mouse movements.
/// @param event encapsulates the event's info.
void OpenGLFrame::mouseMoveEvent(QMouseEvent *event) {
   
   if ((event->buttons() & Qt::MidButton)) { // rotations handler
      AMatrix<float> mT;
      arcball.drag(event->x(), height()-event->y(), &mT);
      sceneT = mT*sceneIniT;
   }
   else if (event->buttons() & Qt::RightButton) { // translations handler
      Vector3 t = screenToWorld(xini, yini, event->x(), height()-event->y());
      AMatrix<float> mT;
      mT.identity();
      mT.translation(t[0], t[1], t[2]);
      sceneT = sceneIniT*mT;
   }
   glDraw();
}

/// Callback for handling mouse button release.
/// @param event encapsulates the event's info.
void OpenGLFrame::mouseReleaseEvent(QMouseEvent *event) {
   
   switch (interactionMode) {
      case VIEW_MODE: {
         break;
      }
   }
   event->accept(); 
}

/// Inplements zoom operations using the mouse wheel
void OpenGLFrame::wheelEvent(QWheelEvent *e) {
   
   //~ if (e->delta()>0) zoomFactor+= 0.1;
   //~ else              zoomFactor-= 0.1;
   //~ e->accept(); 
   //~ setGLview();
   //~ glDraw();
   
   if (e->delta()>0) zoomIn();
   else              zoomOut();
      
   e->accept(); 
}

void OpenGLFrame::keyPressEvent(QKeyEvent *event) {
   
   if (event->key() == Qt::Key_Escape) {
      exit(0);
   }
   
   switch(event->key()) {
      case Qt::Key_Minus:
         --currentFrame;
         if (currentFrame < 0)
            currentFrame = motion->getMotionSize() - 1;
         break;
      case Qt::Key_Plus:
         ++currentFrame;
         if (currentFrame >= motion->getMotionSize())
            currentFrame = 0;
         break;
   }
   glDraw();
}

/// Implements the "zoomin" operation
void OpenGLFrame::zoomIn () {
   
   AMatrix<float> mT;
   mT.identity();
   mT.scaling(1.2);
   sceneT = mT*sceneT;
   
   glDraw();
}

/// Implements the "zoomout" operation
void OpenGLFrame::zoomOut () {
   
   AMatrix<float> mT;
   mT.identity();
   mT.scaling(1.0/1.2);
   sceneT = mT*sceneT;
   
   glDraw();
}

/// Implements the "zoomall" operation
void OpenGLFrame::zoomAll () {
   
   sceneT.identity();
   glDraw();
}

/// Returns the world coordinates of a point in screen space
Point3 OpenGLFrame::screenToWorld(int x, int y) {
   
   glGetIntegerv(GL_VIEWPORT, viewport);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   
   GLdouble xw, yw, zw;
   gluUnProject(x, y, 1.0, mMtx, pMtx, viewport, &xw, &yw, &zw);
   return Point3(xw, yw, zw);
}

/// Returns the translation vector in world coordinates of two points in screen space
Vector3 OpenGLFrame::screenToWorld(int xi, int yi, int xe, int ye) {
   
   glGetIntegerv(GL_VIEWPORT, viewport);
   //~ glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glGetDoublev(GL_MODELVIEW_MATRIX, mMtx);
   
   /// Compute the world coordinates using the orthographic projection
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   glOrtho(-WorldWidth*zoomFactor,  WorldWidth*zoomFactor, 
           -WorldHeight*zoomFactor, WorldHeight*zoomFactor, 
            nearplane, farplane);
   glGetDoublev(GL_PROJECTION_MATRIX, pMtx);
   glPopMatrix();
   
   GLdouble ws[3], we[3]; // project on the near plane
   gluUnProject(xi, yi, 0, mMtx, pMtx, viewport, &ws[0], &ws[1], &ws[2]);
   gluUnProject(xe, ye, 0, mMtx, pMtx, viewport, &we[0], &we[1], &we[2]);
   
   return Vector3(we[0]-ws[0], we[1]-ws[1], we[2]-ws[2]);
}

void OpenGLFrame::animateFrame(int animIndex) {
   
   if(animIndex<0)   currentFrame = 0;
   else              currentFrame = animIndex;
   
   animator->frame(currentFrame);
   
   glDraw();
}
